package com.sinosoft.tencentmapserve.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 腾讯位置服务统一工具类
 * @Author: WangShengJie
 * @Date: 2025/2/19
 */
@Component
public class TencentMapUtils {

    private static final Logger logger = LoggerFactory.getLogger(TencentMapUtils.class);

    @Value("${TencentMap.Key}")
    private String TENCENTMAP_KEY;

    @Value("${TencentMap.SK}")
    private String TENCENTMAP_SK;

    /**
     * 腾讯位置服务要求对GET请求的入参，进行排序：按参数名升序
     * 从而计算 签名 sig
     * @param param 地址入参，包含key
     * @return 返回参数 示例：?app=kfodjf&id=1515,12345&key=445454545&zkj=5555
     */
    public String paramFormat(Map<String,String> param) {
        logger.info("paramFormat：入参：{}", param);
        //遍历Map
        if (ObjectUtils.isEmpty(param)) {
            return null;
        }
        param.put("key", TENCENTMAP_KEY);
        StringBuffer rePara = new StringBuffer();
        try {
            rePara.append("?");
            List<String> keyList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                keyList.add(entry.getKey());
            }
            //根据首字母排序,目前没有忽略大小写
            Collections.sort(keyList);
            for (String key : keyList) {
                rePara.append(key);
                if (StringUtils.isEmpty(param.get(key))) {
                    logger.info("paramFormat：未获取到该key对应value；key:{}",key);
                    return null;
                }
                rePara.append("=" + param.get(key).toString());
                rePara.append("&");
            }
            String finalParam = rePara.toString().substring(0, rePara.toString().length() - 1);
            logger.info("paramFormat：拼接完的参数为：{}",finalParam);
            return finalParam;
        } catch (Exception e) {
            logger.error("paramFormat：参数拼接失败~~", e);
        }
        return null;
    }

    public String paramFormat2(Map<String,String> param) {
        logger.info("paramFormat：入参：{}", param);
        //遍历Map
        if (ObjectUtils.isEmpty(param)) {
            return null;
        }
        param.put("key", "EYIBZ-NKU63-TYD3Y-RWQXI-RA5NF-FKFG5");
        StringBuffer rePara = new StringBuffer();
        try {
            rePara.append("?");
            List<String> keyList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                keyList.add(entry.getKey());
            }
            //根据首字母排序,目前没有忽略大小写
            Collections.sort(keyList);
            for (String key : keyList) {
                rePara.append(key);
                if (StringUtils.isEmpty(param.get(key))) {
                    logger.info("paramFormat：未获取到该key对应value；key:{}",key);
                    return null;
                }
                rePara.append("=" + param.get(key).toString());
                rePara.append("&");
            }
            String finalParam = rePara.toString().substring(0, rePara.toString().length() - 1);
            logger.info("paramFormat：拼接完的参数为：{}",finalParam);
            return finalParam;
        } catch (Exception e) {
            logger.error("paramFormat：参数拼接失败~~", e);
        }
        return null;
    }

    /**
     * 调用腾讯位置服务接口
     * @param url 接口地址
     * @param param 请求参数（不包含key）
     * @return 返回解析后的报文
     */
    public String httpTencentMapServe(String url, Map<String,String> param) {

        String shortUrl = url.replace("https://apis.map.qq.com", "");
        String paramSorted = paramFormat(param);
        if (StringUtils.isEmpty(paramSorted)) {
            logger.info("httpTencentMapServe：排序后的参数为空,原始入参：{}",param);
            return null;
        }
        try {
            String sig = DigestUtils.md5Hex(shortUrl + paramSorted + TENCENTMAP_SK);
            String httpUrl = url + paramSorted + "&sig=" + sig;
            logger.info("httpTencentMapServe：MD5加密获取到的签名sig:{}", sig);
            logger.info("httpTencentMapServe：组织数据：{}", httpUrl);
            String jsonString = HttpUtil.get(httpUrl);
            logger.info("httpTencentMapServe：调取腾讯位置服务接口返回报文：{}", jsonString);
            System.out.println(jsonString);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            String status = jsonObject.getString("status");
            if (org.apache.commons.lang.StringUtils.isBlank(status) || !"0".equals(status)) {
                logger.info("httpTencentMapServe：调取腾讯位置服务未获取到数据~~");
                return null;
            }
            //解析返回报文(有些接口返回数组，有些接口返回对象)
            //直接全部返回
            return jsonString;
        } catch (Exception e) {
            logger.error("httpTencentMapServe：获取腾讯位置服务出错~~",e);
        }
        return null;
    }

    public String httpTencentMapServe2(String url, Map<String,String> param) {

        String shortUrl = url.replace("https://apis.map.qq.com", "");
        String paramSorted = paramFormat2(param);
        if (StringUtils.isEmpty(paramSorted)) {
            logger.info("httpTencentMapServe：排序后的参数为空,原始入参：{}",param);
            return null;
        }
        try {
            String sig = DigestUtils.md5Hex(shortUrl + paramSorted);
            String httpUrl = url + paramSorted;
            logger.info("httpTencentMapServe：MD5加密获取到的签名sig:{}", sig);
            logger.info("httpTencentMapServe：组织数据：{}", httpUrl);
            String jsonString = HttpUtil.get(httpUrl);
            logger.info("httpTencentMapServe：调取腾讯位置服务接口返回报文：{}", jsonString);
            System.out.println(jsonString);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            String status = jsonObject.getString("status");
            if (org.apache.commons.lang.StringUtils.isBlank(status) || !"0".equals(status)) {
                logger.info("httpTencentMapServe：调取腾讯位置服务未获取到数据~~");
                return null;
            }
            //解析返回报文(有些接口返回数组，有些接口返回对象)
            //直接全部返回
            return jsonString;
        } catch (Exception e) {
            logger.error("httpTencentMapServe：获取腾讯位置服务出错~~",e);
        }
        return null;
    }
}
